#include <iostream>
#include <vector>
#include <set>
#include <unordered_map>

using namespace std;

// 3090. 每个字符最多出现两次的最长子字符串
// https://leetcode.cn/problems/maximum-length-substring-with-two-occurrences/description/

class Solution1 {
public:
    int maximumLengthSubstring(string s) {
        int ans = 2;
        int n = s.size();
        int left = 0;
        unordered_map<char, set<int>> recordIndexSetOfCh;
        for (int i = 0; i < n; i++)
        {
            char curCh = s[i];
            recordIndexSetOfCh[curCh].insert(i);


            if (recordIndexSetOfCh[curCh].size() > 2) {
                // 删除最早一次出现的位置
                left = max(left, *recordIndexSetOfCh[curCh].begin() + 1);
                recordIndexSetOfCh[curCh].erase(recordIndexSetOfCh[curCh].begin());
            }
            ans = max(ans, i - left + 1);
        }
        return ans;
    }
};

class Solution {
public:
    int maximumLengthSubstring(string s) {
        unordered_map<char,int>freq;
        int n = s.size();
        int ans = 0;
        int left = 0;
        for (int i = 0; i < n; i++)
        {
            char curCh = s[i];
            freq[curCh]++;
            while(freq[curCh] > 2){
                --freq[s[left++]];
            }
            ans = max(ans, i - left + 1);
        }
        return ans;
    }
};

int main()
{
    return 0;
}